# frozen_string_literal: true
namespace :sidekiq do
  yml_path = -> { File.expand_path('config/sidekiq.yml', Rails.root) }
  log_path = -> { File.expand_path('log/sidekiq.log', Rails.root) }
  pid_path = -> { File.expand_path('tmp/pids/sidekiq.pid', Rails.root) }

  desc 'Start sidekiq'
  task start: :environment do
    print 'Starting sidekiq...'
    cmd =
      <<-START_CMD.strip_heredoc
        if cd "#{Rails.root}" && bundle exec sidekiq -e #{Rails.env} -C "#{yml_path.call}" -L "#{log_path.call}" -P "#{pid_path.call}" -d; then
          echo "Done"
        else
          echo 'Failed'
        fi
      START_CMD
    system cmd
  end

  desc 'Stop sidekiq'
  task stop: :environment do
    print 'Stopping sidekiq...'
    cmd =
      <<-STOP_CMD.strip_heredoc
        if [ -f "#{pid_path.call}" ] && cd "#{Rails.root}" && kill -TERM `cat "#{pid_path.call}"`> /dev/null 2>&1; then
          rm "#{pid_path.call}"
          echo 'Done'
        else
          echo 'Skip (no pid file found)'
        fi
      STOP_CMD
    system cmd
  end

  desc 'Restart sidekiq'
  task restart: [:stop, :start]
end
